﻿<?xml version="1.0" encoding="utf-8"?><Articles><Article><ArticlesID>890</ArticlesID><Title>Tạo một chuỗi ngẫu nhi&amp;#234;n với .net</Title><Body>&amp;lt;p&amp;gt;Để tạo một chuỗi ngẫu nhi&amp;amp;ecirc;n từ c&amp;amp;aacute;c k&amp;amp;yacute; tự A-Za-z0-9 với chiều d&amp;amp;agrave;i t&amp;amp;ugrave;y chọn ch&amp;amp;uacute;ng ta sẽ viết 1 Class RandomStrings như sau:&amp;lt;/p&amp;gt;
&amp;lt;pre class=&amp;quot;brush: csharp;&amp;quot; title=&amp;quot;code&amp;quot;&amp;gt;
class  RandomStrings
   {
      //our default string size
      private const int CONST_MaxStringLenght = 10;

      //our default character string set
      private const string CONST_AllowedCharacterLiterals 
         = &amp;amp;quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890&amp;amp;quot;;

      //our randomizer
      Random randomNumber = new Random();

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Generate a random string using the default options
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the random string&amp;amp;lt;/returns&amp;amp;gt;
      public string GenerateRandomString()
      {
         return GenerateRandomString(CONST_MaxStringLenght);
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Create a random string based on a specified lenght
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;lenght&amp;amp;quot;&amp;amp;gt;the lenght of the desired lenght of the random string&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the randomized string&amp;amp;lt;/returns&amp;amp;gt;
      public string GenerateRandomString(int lenght)
      {
         return GenerateRandomString(lenght, CreateRandomStringSet());
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Creates a random string based on a specific lenght and character set
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;lenght&amp;amp;quot;&amp;amp;gt;the lenght of the desired lenght of the random string&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;charsToUse&amp;amp;quot;&amp;amp;gt;character set to use&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;randomizeSourceSet&amp;amp;quot;&amp;amp;gt;defines whether the source set should be scrambled&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the random string&amp;amp;lt;/returns&amp;amp;gt;
      public string GenerateRandomString(int lenght, string charsToUse, bool randomizeSourceSet)
      {
         string randomString = String.Empty;

         if (randomizeSourceSet) {
            //scramble and jumble it
            randomString = GenerateRandomString(lenght, CreateRandomStringSet(charsToUse));
         }
         else {
            //use the default charset
            randomString = GenerateRandomString(lenght, charsToUse);
         }

         return randomString;
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Creates a random string based on a specific lenght and character set
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;lenght&amp;amp;quot;&amp;amp;gt;the lenght of the desired lenght of the random string&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;charsToUse&amp;amp;quot;&amp;amp;gt;character set to use&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the random string&amp;amp;lt;/returns&amp;amp;gt;
      public string GenerateRandomString(int lenght, string charsToUse)
      {
         //Create a new StringBuilder that would hold the random string.
         StringBuilder randomString = new StringBuilder();

         //Create a variable to hold the generated charater.
         char appendedChar;

         //Create a loop that would iterate from 0 to the specified value of intLenghtOfString
         for (int i = 0; i &amp;amp;lt;= lenght; ++i)
         {
            int characterIndex = Convert.ToInt32(randomNumber.Next(i, charsToUse.Length - i));
            //Generate the char and assign it to appendedChar
            appendedChar = charsToUse[characterIndex];
            //Append appendedChar to randomString
            randomString.Append(appendedChar);
         }
         //Convert randomString to String and return the result.
         return randomString.ToString();
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Returns a random set of characters based on the default literal set
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the random string&amp;amp;lt;/returns&amp;amp;gt;
      private string CreateRandomStringSet()
      {
         //just use the default character set
         return CreateRandomStringSet(CONST_AllowedCharacterLiterals);
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// A function that returns a new set of characters based on an input set
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;allowedCharacters&amp;amp;quot;&amp;amp;gt;the source set&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;the new collection of characters&amp;amp;lt;/returns&amp;amp;gt;
      private string CreateRandomStringSet(string allowedCharacters)
      {
         string randomizedString = String.Empty;

         //get a random string set size
         int randomSetLenght = allowedCharacters.Length * randomNumber.Next(1, CONST_MaxStringLenght);

         //while lenght of the random set is not the same as the source string lenght
         while (randomizedString.Length != randomSetLenght)
         {
            //add a new character
            randomizedString += GetRandomCharFromString(allowedCharacters);
         }

         //return our random string
         return randomizedString;
      }

      /// &amp;amp;lt;summary&amp;amp;gt;
      /// Gets a character from the the input string
      /// &amp;amp;lt;/summary&amp;amp;gt;
      /// &amp;amp;lt;param name=&amp;amp;quot;allowedCharacters&amp;amp;quot;&amp;amp;gt;source string&amp;amp;lt;/param&amp;amp;gt;
      /// &amp;amp;lt;returns&amp;amp;gt;a random character&amp;amp;lt;/returns&amp;amp;gt;
      private char GetRandomCharFromString(string allowedCharacters)
      {
         return allowedCharacters[randomNumber.Next(allowedCharacters.Length - 1)];
      }
   }&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;&amp;amp;nbsp;Sử dụng&amp;lt;/p&amp;gt;
&amp;lt;pre class=&amp;quot;brush: csharp;&amp;quot; title=&amp;quot;code&amp;quot;&amp;gt;
      static  void Main(string[] args)
      {
         RandomStrings r = new RandomStrings();

         Console.WriteLine(r.GenerateRandomString());
         Console.WriteLine(r.GenerateRandomString(10));
         Console.WriteLine(r.GenerateRandomString(10, &amp;amp;quot;qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM&amp;amp;quot;));
         Console.WriteLine(r.GenerateRandomString(10, &amp;amp;quot;[]{}&amp;amp;lt;&amp;amp;gt;!@#$%^&amp;amp;amp;*()qwerttyuioplkjhgfdsazxcvbnm1234567890&amp;amp;quot;, true));
         Console.WriteLine(r.GenerateRandomString(10, &amp;amp;quot;qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM&amp;amp;quot;, false));

         Console.ReadLine();
      }
&amp;lt;/pre&amp;gt;</Body><CommentEnabled>True</CommentEnabled><ViewCount>0</ViewCount><ReleaseDate>4/22/2010 7:18:47 AM</ReleaseDate><TotalComment>0</TotalComment><IsMedia>False</IsMedia><IsPicture>False</IsPicture><IsVote>True</IsVote><ArticlePassword /><PostVisible>0</PostVisible><ArticlePath>/2010/4/16/Tao-mot-chuoi-ngau-nhien-voi-asp-net-37A</ArticlePath><Approved>True</Approved><ImagePath /><CategoryId>28</CategoryId><ArrayCatID>28|25</ArrayCatID></Article></Articles>